import datetime

from django.core import exceptions
from rest_framework import serializers
from db.models import XlzAttention, XlzNews, XlzUser, XlzReplay, XlzReplay2, XlzTopic, XlzImages, XlzLike
from django.db.models import Count


# 用户
from db.models import XlzRemind


class UserSerializer(serializers.ModelSerializer):
    attention = serializers.SerializerMethodField()
    fans = serializers.SerializerMethodField()

    class Meta:
        model = XlzUser
        fields = ('username', 'sex', 'title_image', 'attention', 'fans')

    def get_attention(self, obj):
        return XlzAttention.objects.filter(fans_id=obj.id).aggregate(Count('user_id'))

    def get_fans(self, obj):
        return XlzAttention.objects.filter(user_id=obj.id).aggregate(Count('fans_id'))


# 图片
class ImagesSerializer(serializers.ModelSerializer):
    class Meta:
        model = XlzImages
        fields = ('img_url', 'site_tag', 'brand_tag', 'diy_tag', 'site_tag_location', 'brand_tag_location', 'diy_tag_location')


# 动态消息
class NewsSerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    title_image = serializers.SerializerMethodField()
    comment_count = serializers.SerializerMethodField()
    like_status = serializers.SerializerMethodField()
    topic_tag = serializers.SerializerMethodField()
    img_attribute = serializers.SerializerMethodField()
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = XlzNews
        fields = ('user_name', 'title_image', 'id', 'update_time', 'content', 'img_attribute', 'topic_tag', 'transmit',
                  'like_num', 'like_status', 'comment_count')

    def get_user_name(self, obj):
        return XlzUser.objects.get(id=obj.user_id).username

    def get_title_image(self, obj):
        return XlzUser.objects.get(id=obj.user_id).title_image

    def get_comment_count(self, obj):
        return XlzReplay.objects.filter(comment_id=obj.id).aggregate(Count('id'))

    def get_like_status(self, obj):
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user
        like_status = XlzLike.objects.filter(user_id=user.id, new_id=obj.id)
        if like_status:
            return like_status[0].status
        else:
            return 0

    def get_topic_tag(self, obj):
        tag = XlzTopic.objects.filter(news_id=obj.id)
        if not tag:
            return 0
        else:
            return tag[0].content

    def get_img_attribute(self, obj):
        images_qus = XlzImages.objects.filter(news_id=obj.id)
        return ImagesSerializer(images_qus, many=True).data


# 动态消息
class NewestSerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    title_image = serializers.SerializerMethodField()
    comment_count = serializers.SerializerMethodField()
    like_status = serializers.SerializerMethodField()
    topic_tag = serializers.SerializerMethodField()
    img_attribute = serializers.SerializerMethodField()
    is_attention = serializers.SerializerMethodField()
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')


    class Meta:
        model = XlzNews
        fields = ('user_name', 'title_image', 'id', 'update_time', 'content', 'img_attribute', 'topic_tag',
                  'transmit', 'like_num', 'like_status', 'comment_count', 'is_attention')

    def get_user_name(self, obj):
        return XlzUser.objects.get(id=obj.user_id).username

    def get_title_image(self, obj):
        return XlzUser.objects.get(id=obj.user_id).title_image

    def get_comment_count(self, obj):
        return XlzReplay.objects.filter(comment_id=obj.id).aggregate(Count('id'))

    def get_topic_tag(self, obj):
        tag = XlzTopic.objects.filter(news_id=obj.id)
        if not tag:
            return 0
        else:
            return tag[0].content

    def get_img_attribute(self, obj):
        images_qus = XlzImages.objects.filter(news_id=obj.id)
        return ImagesSerializer(images_qus, many=True).data

    def get_is_attention(self, obj):
        # 获取当前用户id
        uid = self.context['request'].user
        # print(uid.id)
        # 获取用户的关注列表
        att_queryset = XlzAttention.objects.filter(fans_id=uid.id)
        att_list = []
        for que in att_queryset:
            att_list.append(que.user_id)
        if obj.user_id in att_list:
            return 1  # 已关注
        return 0   # 未关注

    def get_like_status(self, obj):
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user
        like_status = XlzLike.objects.filter(user_id=user.id, new_id=obj.id)
        if like_status:
            return like_status[0].status
        else:
            return 0


# 回复
class ReplaySerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    title_image = serializers.SerializerMethodField()

    class Meta:
        model = XlzReplay
        fields = ('user_name', 'title_image', 'id', 'content', 'create_time')

    def get_user_name(self, obj):
        return XlzUser.objects.get(id=obj.user_id).username

    def get_title_image(self, obj):
        return XlzUser.objects.get(id=obj.user_id).title_image


# 回复2
class Replay2Serializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    title_image = serializers.SerializerMethodField()

    class Meta:
        model = XlzReplay2
        fields = ('user_name', 'title_image', 'id', 'comment_id', 'content', 'create_time')

    def get_user_name(self, obj):
        return XlzUser.objects.get(id=obj.user_id).username

    def get_title_image(self, obj):
        return XlzUser.objects.get(id=obj.user_id).title_image


# 新增帖子
class PostingSerializer(serializers.ModelSerializer):
    user_id = serializers.IntegerField()
    topic_id = serializers.IntegerField(required=False)
    content = serializers.CharField(
        min_length=5,
        error_messages={
            'min_length': '请至少输入５个字哦'
        },
        required=True
    )
    transmit = serializers.IntegerField(default=0)
    like_num = serializers.IntegerField(default=0)  # 点赞数
    create_time = serializers.DateTimeField(read_only=True,default=datetime.datetime.now())  # 创建时间
    update_time = serializers.DateTimeField(read_only=True)  # 更新时间
    is_delete = serializers.BooleanField(default=False)

    class Meta:
        model = XlzNews
        fields = ('user_id', 'topic_id', 'content', 'transmit','like_num','create_time',
                  'update_time', 'is_delete'
                  )
    # 局部钩子：validate_要校验的字段名(self, 当前要校验字段的值)
    # 校验规则：可以做一个敏感字过滤，校验失败，抛出异常
    def validate_content(self, value):
        if 'g' in value.lower():  # 名字中不能出现g
            raise exceptions.ValidationError('请重新输入！')
        return value

# 提醒用户记账
class ReminderbookkeepingSerializer(serializers.ModelSerializer):
    remind_time = serializers.DateTimeField(format='%H:%M')

    class Meta:
        model = XlzRemind
        fields = ("id","remind_time")

    def get_remind_time(self,obj):
        return XlzRemind.objects.get(user_id=obj.user_id).remind_time


# 提醒有人评论了用户
class CommentSerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    title_image = serializers.SerializerMethodField()
    news_content = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%m-%d %H:%M')

    class Meta:
        model = XlzReplay
        fields = ('user_name', 'news_content', 'title_image', 'id', 'content',  'create_time')

    def get_user_name(self, obj):
        return XlzUser.objects.get(id=obj.user_id).username

    def get_news_content(self, obj):
        news_que = XlzNews.objects.filter(user_id=obj.user_id)
        return DNewsSerializer(news_que, many=True).data[0]['content']

    def get_title_image(self, obj):
        return XlzUser.objects.get(id=obj.user_id).title_image


class DNewsSerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    title_image = serializers.SerializerMethodField()


    class Meta:
        model = XlzNews
        fields = ('user_name', 'title_image', 'id', 'content')

    def get_user_name(self, obj):
        return XlzUser.objects.get(id=obj.user_id).username

    def get_title_image(self, obj):
        return XlzUser.objects.get(id=obj.user_id).title_image

class TopicSerializer(serializers.ModelSerializer):
    content = serializers.SerializerMethodField()

    class Meta:
        model = XlzTopic
        fields = ('content', 'id')

    def get_content(self, obj):
        return XlzTopic.objects.get(id=obj.id).content



# 用户粉丝信息
class FansSerializer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField()
    title_image = serializers.SerializerMethodField()
    mutual_following = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%m-%d %H:%M')

    class Meta:
        model = XlzUser
        fields = ('user_name', 'title_image', 'create_time', 'mutual_following')

    def get_mutual_following(self, obj):
        # 获取当前用户id
        uid = self.context['request'].user
        # 获取用户的关注列表
        att_queryset = XlzAttention.objects.filter(fans_id=uid.id)
        att_list = []
        fans_list = []
        for que in att_queryset:
            att_list.append(que.user_id)
        for fans in att_list:
            # 获取被关注人的关注列表
            fans_queryset = XlzAttention.objects.filter(fans_id=fans).values('user_id')
            fans_id = ((fans_queryset.values('user_id')[0])['user_id'])
            fans_list.append(fans_id)
        # print(fans_list, att_list)
        if (obj.user_id in fans_list):
            return 1  # 已互相关注
        return 0   # 未互相关注

    def get_user_name(self, obj):
        return XlzUser.objects.get(id=obj.fans_id).username

    def get_title_image(self, obj):
        return XlzUser.objects.get(id=obj.fans_id).title_image

